iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0

今天來解YKL08(UVA100):The 3n + 1 problem

The 3n + 1 problem

https://ithelp.ithome.com.tw/upload/images/20240922/20155574zuYZlJAOj8.png
https://ithelp.ithome.com.tw/upload/images/20240922/20155574afSQ6MoSCy.png

找出介於i和j之間的數
所產生的數列中最大的cycle length

在敘述中已經把演算法列出來了
只需要將計算出序列的number的總和即可

#include <bits/stdc++.h>
using namespace std;

int alg(int n){
	int count = 0;
	while(n != 1){
		if(n % 2 == 1){
			n = 3 * n + 1;
		}else{
			n = n / 2;
		}
		count++;
	}
	count++;
	return count;
}

int main(){
	int i,j;
	
	while(cin >> i >> j){
		vector<int> arr;
		cout << i << " " << j ;
		if(i > j){
			int tmp;
			tmp = j;
			j = i;
			i = tmp;
		}
		
		for(i ;i <= j;i++){
			arr.push_back(alg(i));
		}
		cout << " " << *max_element(arr.begin(),arr.end()) << endl;
	}

	return 0;
}

上一篇
CPE C++ 刷題 Day 7
下一篇
CPE C++ 刷題 Day 9
系列文
CPE C++ 刷題20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言